package ldh.im.server.initialize;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import ldh.im.ImConfig;
import ldh.im.base.handler.*;
import ldh.im.base.handler.service.HandlerService;
import ldh.im.base.handler.service.ThreadHandlerService;
import ldh.im.handle.ExceptionInHandler;
import ldh.im.handle.ExceptionOutHandler;
import ldh.im.server.handler.TransferDataServerCoderHandler;

import java.util.concurrent.TimeUnit;

public class ImChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final int MAX_LENGTH = 1024 * 256;  // 256k

    private HandlerService handlerService = new ThreadHandlerService(Runtime.getRuntime().availableProcessors());

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline
//                .addLast(new IdleStateHandler(5,20,30, TimeUnit.MINUTES))
                .addLast(new HeartBeatServerHandler())
                .addLast(new ExceptionOutHandler())
                .addLast(new LoggingHandler(LogLevel.DEBUG))  // 打印连接信息
                .addLast(new LengthFieldBasedFrameDecoder(MAX_LENGTH, ImConfig.SERVER_HEAD_FIELD, 4))
//                .addLast(new ImServerCheckHandler())            // 验证数据的合法性
                .addLast(new ImSessionHandler())
                .addLast(new TransferDataServerCoderHandler())  // 转码
                .addLast(new ToCoderHandler())                  // 转对象
                .addLast(new ToHandler(handlerService))
                .addLast(new ExitResponseHandler())
//                .addLast(new PriorityQueueHandler())
//                .addLast(new LoginHandler())                    // 登录业务
//                .addLast(new ReConnectionHandler())             // 重连
//                .addLast(new TextMessageHandler())              // 发送消息
//                .addLast(new ExitHandler())
                .addLast(new ExceptionInHandler())
        ;
    }
}
